﻿var updateUserProfileVM = {
    ID: ko.observable(),
    SocialID: ko.observable(),
    SocialIDException: ko.observable(),
    Name: ko.observable(),
    NameException: ko.observable(),
    Days: ko.observableArray(DayArrays[3]),
    SelectedDay: ko.observable(),
    Months: ko.observableArray(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']),
    SelectedMonth: ko.observable(),
    Year: ko.observable(),
    BirthdayException: ko.observable(),
    Male: ko.observable(),
    Address: ko.observable(),
    AddressException: ko.observable(),
    Phone: ko.observable(),
    PhoneException: ko.observable(),
    UserTypes: ko.observableArray([]),
    SelectedUserType: ko.observable(),
    clearOldData: function () {
        this.ID('');
        this.SocialID('');
        this.Name('');
        this.Days(DayArrays[3]);
        this.SelectedDay(null);
        this.SelectedMonth(null);
        this.Year('');
        this.Male(false);
        this.Address('');
        this.Phone('');
        this.SelectedUserType('Patient');
        this.clearOldException();
    },
    loadRequest: null,
    cancelLoadRequest: function () {
        if (this.loadRequest != null) {
            this.loadRequest.abort();
        }
    },
    loadData: function (userID, indexController) {
        var self = this;
        self.clearOldData();
        indexController.message.processing("processing");
        indexController.enableBtnUpdateUserUpdate(false);
        self.loadRequest = $.ajax({
            type: 'post',
            url: home + '/' + userType + '/GetUser',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify({id: userID}),
            success: function (data) {
                self.ID(data[0].ID);
                self.SocialID(data[0].SocialID);
                self.Name(data[0].Name);
                var b = data[0].Birthday.split('/');
                self.SelectedDay(parseInt(b[0]));
                self.SelectedMonth(parseInt(b[1]));
                self.Year(parseInt(b[2]));
                self.Male(data[0].Male);
                self.Address(data[0].Address);
                if (data[0].Phone != null) {//invalid phone exception
                    self.Phone(data[0].Phone);
                }
                self.UserTypes(data[1]);
                self.SelectedUserType(data[0].UserType);
                indexController.enableBtnUpdateUserUpdate(true);
                indexController.message.processComplete("process_complete");
            },
            error: function (err) {
                if (err.status == 200) {
                    indexController.message.processComplete(err.responseText);
                }
                else {
                    indexController.message.processComplete("process_error");
                }
            },
            complete: function (xhr, textStatus) {
            }
        });
    },
    clearOldException: function () {
        this.SocialIDException('');
        this.NameException('');
        this.BirthdayException('');
        this.AddressException('');
        this.PhoneException('');
    },
    validNumberOrEmpty: function (str) {
        var pattern = /^\d*$/g;//new RegExp("^\d+$");
        if (!pattern.test(str)) {
            return false;
        }
        return true;
    },
    validYear: function () {
        var self = this;
        var year = $("#UpdateUserProfileYear").val();
        if (self.validNumberOrEmpty(year) == false || year < 1753 || year > 9999) {
            return false;
        }
        return true;
    },
    namNhuan: function () {
        var year = $("#UpdateUserProfileYear").val();
        if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
            return true;
        }
        return false;
    },
    updateUser: function (indexController) {
        var self = this;
        self.clearOldException();
        var flag = true;
        if (self.Name().length == 0) {
            self.NameException(messageController.messageData["type_userName"].text);
            flag = false;
        }
        if (self.SelectedDay() == null || self.SelectedMonth() == null || self.validYear() == false
            || MonthDay[self.SelectedMonth()] < self.SelectedDay()
            || (self.SelectedMonth() == 2 && self.namNhuan() == false && self.SelectedDay() > 28)
            || (self.SelectedMonth() == 2 && self.namNhuan() == true && self.SelectedDay() > 29)
            ) {
            self.BirthdayException(messageController.messageData["select_birthday"].text);
            flag = false;
        }
        if (self.Address().length == 0) {
            self.AddressException(messageController.messageData["type_userAddress"].text);
            flag = false;
        }
        if (self.validNumberOrEmpty(self.Phone()) == false) {
            self.PhoneException(messageController.messageData["invalid_phone"].text);
            flag = false;
        }
        if (flag == false) {
            return;
        }
        indexController.enableBtnUpdateUserUpdate(false);
        indexController.enableBtnUpdateUserCancel(false);
        indexController.message.processing("processing");
        $.ajax({
            type: 'post',
            url: home + '/' + userType + '/UpdateUser',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify({
                ID: self.ID(), SocialID: self.SocialID(), Name: self.Name(), BirthDay: UpdateBirthday(),
                Male: self.Male(), Address: self.Address(), Phone: self.Phone(), UserType: self.SelectedUserType()
            }),
            success: function (data) {
                self.clearOldData();
                findUserVM.ID(data.ID);
                findUserVM.SocialID(data.SocialID);
                findUserVM.Name(data.Name);
                findUserVM.Birthday(data.Birthday);
                findUserVM.Male(data.Male);
                findUserVM.Address(data.Address);
                findUserVM.Phone(data.Phone);
                indexController.displayUpdateUserProfileForm(false);
                indexController.message.processComplete("save_success");
            },
            error: function (err) {
                if (err.status == 200) {
                    messageController.processComplete(err.responseText);
                    if (err.responseText == "exist_socialid") {
                        self.SocialIDException(messageController.messageData["exist_socialid"].text);
                        $("#UpdateUserProfile #SocialID").focus();
                    }
                }
                else {
                    indexController.message.processComplete("save_fail");
                }
            },
            complete: function (xhr, textStatus) {
                indexController.enableBtnUpdateUserUpdate(true);
                indexController.enableBtnUpdateUserCancel(true);
            }
        });
    }
};
var UpdateBirthday = ko.computed(function () {
    return updateUserProfileVM.SelectedDay() + '/' + updateUserProfileVM.SelectedMonth() + '/' + updateUserProfileVM.Year();
});